package com.example.springwebfluxdoc.controller;

import com.example.springwebfluxdoc.model.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 用户控制器示例
 * 提供用户管理相关的REST API接口
 */
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户信息的增删改查等操作")
public class UserController {

    // 模拟数据库存储用户信息
    private final Map<Long, User> userStore = new HashMap<>();
    private final AtomicLong counter = new AtomicLong(0);

    public UserController() {
        // 初始化一些测试数据
        userStore.put(1L, new User(1L, "张三", "zhangsan@example.com", 25));
        userStore.put(2L, new User(2L, "李四", "lisi@example.com", 30));
        counter.set(2);
    }

    /**
     * 获取所有用户列表
     * 支持服务器发送事件(SSE)流式响应
     */
    @Operation(summary = "获取所有用户", description = "返回系统中所有用户的列表，支持SSE流式响应")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", 
                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class))))
    })
    @GetMapping(produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_EVENT_STREAM_VALUE})
    public Flux<User> getAllUsers() {
        // 模拟延迟，每秒返回一个用户
        return Flux.fromIterable(userStore.values())
                .delayElements(Duration.ofSeconds(1));
    }

    /**
     * 根据ID获取单个用户
     */
    @Operation(summary = "根据ID获取用户", description = "根据用户ID查询指定用户的详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", 
                    content = @Content(schema = @Schema(implementation = User.class))),
            @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @GetMapping("/{id}")
    public Mono<ResponseEntity<User>> getUserById(
            @Parameter(description = "用户ID", required = true, example = "1") @PathVariable Long id) {
        User user = userStore.get(id);
        if (user != null) {
            return Mono.just(ResponseEntity.ok(user));
        } else {
            return Mono.just(ResponseEntity.notFound().build());
        }
    }

    /**
     * 创建新用户
     */
    @Operation(summary = "创建新用户", description = "添加一个新用户到系统中")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "创建成功", 
                    content = @Content(schema = @Schema(implementation = User.class)))
    })
    @PostMapping
    public Mono<User> createUser(
            @Parameter(description = "用户信息", required = true) @RequestBody User user) {
        long id = counter.incrementAndGet();
        user.setId(id);
        userStore.put(id, user);
        return Mono.just(user);
    }

    /**
     * 更新现有用户
     */
    @Operation(summary = "更新用户信息", description = "根据用户ID更新指定用户的详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功", 
                    content = @Content(schema = @Schema(implementation = User.class))),
            @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @PutMapping("/{id}")
    public Mono<ResponseEntity<User>> updateUser(
            @Parameter(description = "用户ID", required = true, example = "1") @PathVariable Long id,
            @Parameter(description = "更新后的用户信息", required = true) @RequestBody User user) {
        if (userStore.containsKey(id)) {
            user.setId(id);
            userStore.put(id, user);
            return Mono.just(ResponseEntity.ok(user));
        } else {
            return Mono.just(ResponseEntity.notFound().build());
        }
    }

    /**
     * 删除用户
     */
    @Operation(summary = "删除用户", description = "根据用户ID删除指定用户")
    @ApiResponses({
            @ApiResponse(responseCode = "204", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @DeleteMapping("/{id}")
    public Mono<ResponseEntity<Void>> deleteUser(
            @Parameter(description = "用户ID", required = true, example = "1") @PathVariable Long id) {
        if (userStore.containsKey(id)) {
            userStore.remove(id);
            return Mono.just(ResponseEntity.noContent().build());
        } else {
            return Mono.just(ResponseEntity.notFound().build());
        }
    }

}